<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="基础," />










<meta name="description" content="日/夜模式切换作为一个App的基本功能经常会被使用到，接下来就举出一些常用的日/夜模式切换的方法">
<meta name="keywords" content="基础">
<meta property="og:type" content="article">
<meta property="og:title" content="日&#x2F;夜模式切换">
<meta property="og:url" content="http://yoursite.com/2017/03/13/日夜模式切换/index.html">
<meta property="og:site_name" content="SISYPHUSER">
<meta property="og:description" content="日/夜模式切换作为一个App的基本功能经常会被使用到，接下来就举出一些常用的日/夜模式切换的方法">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://7xtcmn.com1.z0.glb.clouddn.com/UIMode_1.png">
<meta property="og:image" content="http://7xtcmn.com1.z0.glb.clouddn.com/UIMode_2.png">
<meta property="og:image" content="http://7xtcmn.com1.z0.glb.clouddn.com/UIMode_3.gif">
<meta property="og:image" content="http://7xtcmn.com1.z0.glb.clouddn.com/Lib.gif">
<meta property="og:updated_time" content="2018-03-03T05:21:44.491Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="日&#x2F;夜模式切换">
<meta name="twitter:description" content="日/夜模式切换作为一个App的基本功能经常会被使用到，接下来就举出一些常用的日/夜模式切换的方法">
<meta name="twitter:image" content="http://7xtcmn.com1.z0.glb.clouddn.com/UIMode_1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/03/13/日夜模式切换/"/>





  <title>日/夜模式切换 | SISYPHUSER</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">SISYPHUSER</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-word">
          <a href="/word/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />
            
            word
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/03/13/日夜模式切换/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Andy">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="SISYPHUSER">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">日/夜模式切换</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-13T15:34:40+08:00">
                2017-03-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>日/夜模式切换作为一个App的基本功能经常会被使用到，接下来就举出一些常用的日/夜模式切换的方法</p>
<a id="more"></a>
<p><strong>使用UIMode的方法</strong><br>这种方式操作起来比较简单，就是将不同模式下的资源分开存放，然后调用方法切换资源即可</p>
<ul>
<li><em>资源存放的路径</em></li>
</ul>
<p><img src="http://7xtcmn.com1.z0.glb.clouddn.com/UIMode_1.png" alt="pic"></p>
<p><img src="http://7xtcmn.com1.z0.glb.clouddn.com/UIMode_2.png" alt="pic"></p>
<ul>
<li><em>切换资源的方法</em></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">if (isNight) &#123;</span><br><span class="line">	AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);</span><br><span class="line">&#125; else &#123;</span><br><span class="line">	AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);</span><br><span class="line">&#125;</span><br><span class="line">recreate();</span><br></pre></td></tr></table></figure>
<p>其中AppCompatDelegate.MODE_NIGHT_YES代表切换到夜间模式，AppCompatDelegate.MODE_NIGHT_NO代表切换到日间模式<br>如果是在新的Activity中切换日/夜模式则需要用RxBus(关于RxBus的用法可以参照我上篇博客)通知在后台的Activity调用recreate()重启Activity</p>
<ul>
<li><em>最终效果</em></li>
</ul>
<p><img src="http://7xtcmn.com1.z0.glb.clouddn.com/UIMode_3.gif" alt="gif"></p>
<ul>
<li><em>存在问题</em></li>
</ul>
<p>由于需要recreate(),会重绘Activity导致屏幕闪烁，重新加载Avtivity时需要注意Activity内元素的保存</p>
<p><strong>使用Theme</strong><br>通过切换不同的主题来实现切换日/夜模式的效果</p>
<ul>
<li><em>在attrs.xml中设置主题中需要替换资源</em></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;resources&gt;</span><br><span class="line">    &lt;attr name=&quot;bg&quot; format=&quot;color&quot;&gt;&lt;/attr&gt;</span><br><span class="line">    &lt;attr name=&quot;button_bg&quot; format=&quot;color&quot;&gt;&lt;/attr&gt;</span><br><span class="line">    &lt;attr name=&quot;button_tv&quot; format=&quot;color&quot;&gt;&lt;/attr&gt;</span><br><span class="line">&lt;/resources&gt;</span><br></pre></td></tr></table></figure>
<ul>
<li><em>设置日/夜模式主题</em></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"> &lt;style name=&quot;Day&quot; parent=&quot;AppTheme&quot;&gt;</span><br><span class="line">	&lt;item name=&quot;bg&quot;&gt;#FFFFFF&lt;/item&gt;</span><br><span class="line">	&lt;item name=&quot;button_bg&quot;&gt;#A9A9A9&lt;/item&gt;</span><br><span class="line">	&lt;item name=&quot;button_tv&quot;&gt;#000000&lt;/item&gt;</span><br><span class="line">	&lt;item name=&quot;colorPrimary&quot;&gt;@color/colorPrimary&lt;/item&gt;</span><br><span class="line">	&lt;item name=&quot;colorPrimaryDark&quot;&gt;@color/colorPrimaryDark&lt;/item&gt;</span><br><span class="line">&lt;/style&gt;</span><br><span class="line"></span><br><span class="line">&lt;style name=&quot;Night&quot; parent=&quot;AppTheme&quot;&gt;</span><br><span class="line">	&lt;item name=&quot;bg&quot;&gt;#4F4F4F&lt;/item&gt;</span><br><span class="line">	&lt;item name=&quot;button_bg&quot;&gt;#000000&lt;/item&gt;</span><br><span class="line">	&lt;item name=&quot;button_tv&quot;&gt;#FFFFFF&lt;/item&gt;</span><br><span class="line">	&lt;item name=&quot;colorPrimary&quot;&gt;#828282&lt;/item&gt;</span><br><span class="line">	&lt;item name=&quot;colorPrimaryDark&quot;&gt;#828282&lt;/item&gt;</span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure>
<ul>
<li><em>在layout文件中使用arrts中的资源属性</em></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">android:backgroundTint=&quot;?attr/button_bg&quot;</span><br></pre></td></tr></table></figure>
<ul>
<li><em>在Activity中切换主题</em></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"> if(isNight)&#123;</span><br><span class="line">	setTheme(R.style.Night);</span><br><span class="line">&#125;else&#123;</span><br><span class="line">	setTheme(R.style.Day);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>设置主题需要放在setContentView()之前，所以每次切换完日/夜模式后都需要重新加载Activity</p>
<ul>
<li><em>存在问题</em></li>
</ul>
<p>与UIMode方法相同由于需要recreate(),会重绘Activity导致屏幕闪烁，并且在有比较多的属性需要修改时会导致style比较复杂</p>
<p>为了决解改变日/夜模式后屏幕闪烁的问题，我看了不少博客，终于找到了一个比较符合要求的项目，能够实现uiMode方法的不重建Activity切换日/夜模式。<br>项目地址：<a href="https://github.com/geminiwen/SkinSprite" target="_blank" rel="noopener">https://github.com/geminiwen/SkinSprite</a></p>
<p>效果：<br><img src="http://7xtcmn.com1.z0.glb.clouddn.com/Lib.gif" alt="gif"></p>
<p>具体思路是在Activity创建View的过程中注入自己的代码。<br>接下来分析一下这个lib的具体代码</p>
<ul>
<li><em>首先是SkinnableActivity，继承自AppCompatActivity，在这个Activity中对View的创建进行拦截，我们主要关注三个方法</em></li>
</ul>
<p>1)<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">protected void onCreate(@Nullable Bundle savedInstanceState) &#123;</span><br><span class="line">	LayoutInflater layoutInflater = LayoutInflater.from(this);</span><br><span class="line">	LayoutInflaterCompat.setFactory(layoutInflater, this);</span><br><span class="line">	super.onCreate(savedInstanceState);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>注入自己的LayoutInflatorFactory，使inflate在这个LayoutInflaterFactory中执行</p>
<p>2)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public View onCreateView(View parent, String name, Context context, AttributeSet attrs) &#123;</span><br><span class="line">	if (mSkinnableViewInflater == null) &#123;</span><br><span class="line">		mSkinnableViewInflater = new SkinnableViewInflater();</span><br><span class="line">	&#125;</span><br><span class="line">	final boolean isPre21 = Build.VERSION.SDK_INT &lt; 21;</span><br><span class="line">	final boolean inheritContext = isPre21 &amp;&amp; shouldInheritContext((ViewParent) parent);</span><br><span class="line">	return mSkinnableViewInflater.createView(parent, name, context, attrs, inheritContext,</span><br><span class="line">	isPre21, /* Only read android:theme pre-L (L+ handles this anyway) */</span><br><span class="line">	true, /* Read read app:theme as a fallback at all times for legacy reasons */</span><br><span class="line">	VectorEnabledTintResources.shouldBeUsed() /* Only tint wrap the context if enabled */</span><br><span class="line">	);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是具体需要创建View的方法，可以看到他将具体的创建逻辑放到了SkinnableViewInflater中，这个类之后在做分析</p>
<p>3)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public void setDayNightMode(@AppCompatDelegate.NightMode int nightMode) &#123;</span><br><span class="line">	final boolean isPost21 = Build.VERSION.SDK_INT &gt;= 21;</span><br><span class="line"></span><br><span class="line">	getDelegate().setLocalNightMode(nightMode);</span><br><span class="line"></span><br><span class="line">	if (isPost21) &#123;</span><br><span class="line">		applyDayNightForStatusBar();</span><br><span class="line">		applyDayNightForActionBar();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	View decorView = getWindow().getDecorView();</span><br><span class="line">	applyDayNightForView(decorView);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是一个我们之后需要切换日夜模式需要调用的方法，其中主要调用逻辑有<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">getDelegate().setLocalNightMode(nightMode);</span><br></pre></td></tr></table></figure></p>
<p>对系统日/夜模式的资源进行切换</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">if (isPost21) &#123;</span><br><span class="line">	applyDayNightForStatusBar();</span><br><span class="line">	applyDayNightForActionBar();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果api等级大于等于21（即5.0及以上版本）则更换状态栏和标题栏资源<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">applyDayNightForView(decorView);</span><br></pre></td></tr></table></figure></p>
<p>对于内容中的日/夜资源进行切换，这个方法我们可以看下他的具体实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">private void applyDayNightForView(View view) &#123;</span><br><span class="line">	if (view instanceof Skinnable) &#123;</span><br><span class="line">		Skinnable skinnable = (Skinnable) view;</span><br><span class="line">		if (skinnable.isSkinnable()) &#123;</span><br><span class="line">			skinnable.applyDayNight();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	if (view instanceof ViewGroup) &#123;</span><br><span class="line">		ViewGroup parent = (ViewGroup)view;</span><br><span class="line">		int childCount = parent.getChildCount();</span><br><span class="line">		for (int i = 0; i &lt; childCount; i++) &#123;</span><br><span class="line">			applyDayNightForView(parent.getChildAt(i));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到这是一个递归的方法，功能是遍历了view下所有的子view，对实现了Skinnable接口并且isSkinnable()返回true的view调用applyDayNight()。可以猜想到这些View就是自定义的View，这个applyDayNight()就是刷新View中资源的方法。</p>
<ul>
<li><em>接下来可以看下上面的SkinnableViewInflater这个类</em></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line">public final View createView(View parent, final String name, @NonNull Context context,@NonNull AttributeSet attrs, boolean inheritContext,boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) &#123;</span><br><span class="line">    final Context originalContext = context;</span><br><span class="line"></span><br><span class="line">    // We can emulate Lollipop&apos;s android:theme attribute propagating down the view hierarchy</span><br><span class="line">    // by using the parent&apos;s context</span><br><span class="line">    if (inheritContext &amp;&amp; parent != null) &#123;</span><br><span class="line">        context = parent.getContext();</span><br><span class="line">    &#125;</span><br><span class="line">    if (readAndroidTheme || readAppTheme) &#123;</span><br><span class="line">        // We then apply the theme on the context, if specified</span><br><span class="line">        context = themifyContext(context, attrs, readAndroidTheme, readAppTheme);</span><br><span class="line">    &#125;</span><br><span class="line">    if (wrapContext) &#123;</span><br><span class="line">        context = TintContextWrapper.wrap(context);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    View view = null;</span><br><span class="line"></span><br><span class="line">    // We need to &apos;inject&apos; our tint aware Views in place of the standard framework versions</span><br><span class="line">    switch (name) &#123;</span><br><span class="line">        case &quot;TextView&quot;:</span><br><span class="line">            view = new SkinnableTextView(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;ImageView&quot;:</span><br><span class="line">            view = new AppCompatImageView(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;Button&quot;:</span><br><span class="line">            view = new SkinnableButton(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;EditText&quot;:</span><br><span class="line">            view = new AppCompatEditText(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;Spinner&quot;:</span><br><span class="line">            view = new AppCompatSpinner(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;ImageButton&quot;:</span><br><span class="line">            view = new AppCompatImageButton(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;CheckBox&quot;:</span><br><span class="line">            view = new AppCompatCheckBox(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;RadioButton&quot;:</span><br><span class="line">            view = new AppCompatRadioButton(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;CheckedTextView&quot;:</span><br><span class="line">            view = new AppCompatCheckedTextView(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;AutoCompleteTextView&quot;:</span><br><span class="line">            view = new AppCompatAutoCompleteTextView(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;MultiAutoCompleteTextView&quot;:</span><br><span class="line">            view = new AppCompatMultiAutoCompleteTextView(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;RatingBar&quot;:</span><br><span class="line">            view = new AppCompatRatingBar(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;SeekBar&quot;:</span><br><span class="line">            view = new AppCompatSeekBar(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;LinearLayout&quot;:</span><br><span class="line">            view = new SkinnableLinearLayout(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;FrameLayout&quot;:</span><br><span class="line">            view = new SkinnableFrameLayout(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;RelativeLayout&quot;:</span><br><span class="line">            view = new SkinnableRelativeLayout(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">        case &quot;android.support.v7.widget.Toolbar&quot;:</span><br><span class="line">            view = new SkinnableToolbar(context, attrs);</span><br><span class="line">            break;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    if (view == null &amp;&amp; originalContext != context) &#123;</span><br><span class="line">        // If the original context does not equal our themed context, then we need to manually</span><br><span class="line">        // inflate it using the name so that android:theme takes effect.</span><br><span class="line">        view = createViewFromTag(context, name, attrs);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    if (view != null) &#123;</span><br><span class="line">        // If we have created a view, check it&apos;s android:onClick</span><br><span class="line">        checkOnClickListener(view, attrs);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    return view;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个是SkinnableViewInflater中最主要的方法，根据name创建出不同的View，即自定义的View，这里并没有把所有的view都做出来，但是都大同小异，如果不够用还可以自己添加</p>
<ul>
<li><em>最后只剩下View的没有看了，由于View比较多而且其中的内容都相似，我们拿SkinnableLinearLayout作为案例进行研究</em></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">public SkinnableLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) &#123;</span><br><span class="line">    super(context, attrs, defStyleAttr);</span><br><span class="line"></span><br><span class="line">    mAttrsHelper = new AttrsHelper();</span><br><span class="line">    TypedArray a = context.obtainStyledAttributes(attrs,</span><br><span class="line">            R.styleable.SkinnableView,</span><br><span class="line">            defStyleAttr, 0);</span><br><span class="line">    mAttrsHelper.storeAttributeResource(a, R.styleable.SkinnableView);</span><br><span class="line">    a.recycle();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@Override</span><br><span class="line">public void applyDayNight() &#123;</span><br><span class="line">    Context context = getContext();</span><br><span class="line">    int key;</span><br><span class="line"></span><br><span class="line">    key = R.styleable.SkinnableView[R.styleable.SkinnableView_android_background];</span><br><span class="line">    int backgroundResource = mAttrsHelper.getAttributeResource(key);</span><br><span class="line">    if (backgroundResource &gt; 0) &#123;</span><br><span class="line">        Drawable background = ContextCompat.getDrawable(context, backgroundResource);</span><br><span class="line">        if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.JELLY_BEAN) &#123;</span><br><span class="line">            setBackgroundDrawable(background);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            setBackground(background);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>SkinnableLinearLayout中的思路也比较简单，在构造方法中向mAttrsHelper添加如属性，在需要刷新是再从mAttrsHelper中取出。对于不同的View也只是属性的内容不同而已</p>
<p>至此就是这个项目的大致源码，然后只需要将Activity继承SkinnableActivity,将uiMode中的<br>AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);<br>改为<br> setDayNightMode(AppCompatDelegate.MODE_NIGHT_YES);<br> 并且不需要调用recreate()方法。需要注意的是还需要在该Activity中添加上android:configChanges=”uiMode”。</p>
<p>结语：这是我第一次写关于阅读源码的博客，尽管选了一个比较简单的lib但还是表达得比较凌乱。我之后还是会多多尝试写这方面的博客，努力提高自己的水平。</p>
<p><strong>参考博客：</strong><br><a href="https://segmentfault.com/a/1190000005736047" target="_blank" rel="noopener">android 实现【夜晚模式】的另外一种思路</a><br><a href="http://blog.csdn.net/u012572538/article/details/38726549" target="_blank" rel="noopener">Android通过改变主题实现夜间模式</a><br><a href="http://www.jb51.net/article/93852.htm" target="_blank" rel="noopener">Android实现日夜间模式的深入理解</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/基础/" rel="tag"># 基础</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/08/基于RxJava的RxBus/" rel="next" title="基于RxJava的RxBus">
                <i class="fa fa-chevron-left"></i> 基于RxJava的RxBus
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/16/Dagger2使用/" rel="prev" title="Dagger2使用">
                Dagger2使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="Andy" />
            
              <p class="site-author-name" itemprop="name">Andy</p>
              <p class="site-description motion-element" itemprop="description">Something Wrong</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Andy</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
